package common;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Hashtable;

/**
 * @author ：daiyuanbao
 * @date ：Created in 2022/7/19 11:45
 * @description：生成二维码
 */
public class QRCodeGenerator {
    //二维码图片的宽度
    private static int WIDTH = 300;
    //二维码图片的高度
    private static int HEIGHT = 300;

    public static String generateQRCodeImage(String profile,String content) throws Exception {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//H最高容错等级
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

        BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT,hints);
        String url="/QRCode/"+content+".PNG";
        Path path = FileSystems.getDefault().getPath(profile+url);

        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
        return url;
    }
}
